﻿using System.Collections.Generic;
using System.Linq;
using System;

using MvcCms.Data;


namespace MvcCmsWiki.Data
{
    public class EntityWikiRepository : IWikiRepository
    {
        #region Constructors

        private readonly MvcCmsEntities _entities;

        //public EntityWikiRepository()
        //    : this(new EntitiesProvider())
        //{
        //}

        public EntityWikiRepository(IEntitiesProvider entitiesProvider)
        {
            _entities = entitiesProvider.GetEntityContext();
        }
        #endregion

        public WikiContent Get(string slug, int portalId)
        {
            return (from s in _entities.WikiContentSet 
                    .Include("WikiTitle")
                    where s.WikiTitle.Slug.ToLower() == slug.ToLower() &&
                    s.WikiTitle.Portal.PortalID == portalId 
                    orderby s.Version descending 
                    select s).FirstOrDefault();
        }
        public WikiSetting GetSettings(int portalId)
        {
            return (from s in _entities.WikiSettingSet 
                    where s.Portal.PortalID == portalId 
                    select s).FirstOrDefault();
        }

        private WikiSetting GetSettingsByID(int settingId)
        {
            return (from s in _entities.WikiSettingSet                    
                    where s.WikiSettingID == settingId
                    select s).FirstOrDefault();
        }
        public WikiTitle GetTitle(int titleId)
        {
            return (from s in _entities.WikiTitleSet 
                    .Include("WikiContents")
                    where s.TitleID == titleId 
                    select s).FirstOrDefault();
        }
        public WikiContent GetByVersion(string slug, int version, int portalId)
        {
            return (from s in _entities.WikiContentSet
                    .Include("WikiTitle")
                    where s.WikiTitle.Slug.ToLower() == slug.ToLower() &&
                    s.Version == version &&
                    s.WikiTitle.Portal.PortalID == portalId 
                    select s).FirstOrDefault();
        }
        public IEnumerable<WikiContent> GetHistory(Guid userId)
        {
            return (from c in _entities.WikiContentSet
                   .Include("WikiTitle")
                    where c.User.UserID == userId 
                    orderby c.ContentID descending 
                    select c).Take(10).ToList();
        }
        public IEnumerable<WikiContent> GetHistory(string slug, int portalId)
        {
            return (from c in _entities.WikiContentSet 
                   .Include("WikiTitle")
                   .Include("User")
                    where c.WikiTitle.Slug.ToLower() == slug.ToLower() &&
                   c.WikiTitle.Portal.PortalID == portalId 
                   select c);
        }
        public void EditWikiSettings(WikiSetting wikiSettingToEdit)
        {
            var originalSettings = GetSettingsByID(wikiSettingToEdit.WikiSettingID);

            originalSettings.AllowAnonymousCreate = wikiSettingToEdit.AllowAnonymousCreate;
            originalSettings.AllowAnonymousEdit = wikiSettingToEdit.AllowAnonymousEdit;
            originalSettings.RoleForCreate = wikiSettingToEdit.RoleForCreate;
            originalSettings.RoleForEdit = wikiSettingToEdit.RoleForEdit;
            // Save changes
            _entities.WikiSettingSet.ApplyCurrentValues(wikiSettingToEdit);
            _entities.SaveChanges();
        }
        public void CreateWikiSettings(WikiSetting wikiSettingToCreate)
        {
            _entities.WikiSettingSet.AddObject(wikiSettingToCreate);
            _entities.SaveChanges();
        }
        public void Save(string slug, string title, string source, Portal portal, User user, string restrictedToGroups)
        {
            var wikiTitle = (from s in _entities.WikiTitleSet 
                             .Include("Portal")
                             .Include("WikiContents")
                    where s.Slug == slug &&
                    s.Portal.PortalID == portal.PortalID 
                    select s).FirstOrDefault();
            WikiContent oldVersion = null;
            int contentCount=0;
            if (wikiTitle == null)
            {
                wikiTitle = new WikiTitle
                {
                    Slug = slug,
                    Name = title,
                    Portal = portal,
                    User = user,
                    RestrictedToGroups = restrictedToGroups 
                };

                _entities.WikiTitleSet.AddObject(wikiTitle);
                _entities.SaveChanges();
            }
            else
            {
                contentCount = wikiTitle.WikiContents.Count;
                var wikiContents = wikiTitle.WikiContents.OrderByDescending(content => content.Version);
                if (wikiContents.Count() > 0)
                {
                    oldVersion = wikiContents.First();
                }
            }
            
            var newWikiContent = new WikiContent
            {
                Source = source,
                Version = contentCount+1,
                VersionDate = DateTime.Now,
                WikiTitle = wikiTitle,
                User = user,
                IsCurrentVersion = true
            };

            _entities.WikiContentSet.AddObject(newWikiContent);
            _entities.SaveChanges();

            if (contentCount > 0)
            {
                oldVersion.IsCurrentVersion = false;
                _entities.WikiContentSet.ApplyCurrentValues(oldVersion);
                _entities.SaveChanges();
            }
        }
    }
}